package com.dw.producer;

import com.dw.model.message.TestMessage;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
public class MqProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 同步发送消息
     */
    public SendResult sendSyncMessage(String topic, String tag, TestMessage message) {
        // 同步发送消息
        String destination = topic + ":" + tag;
        return rocketMQTemplate.syncSend(destination, MessageBuilder.withPayload(message).build());
    }


    /**
     * 同步发送延时消息
     */
    public SendResult sendSyncDelayMessage(String topic, String message, int delayLevel) {
        return rocketMQTemplate.syncSend(topic,
                MessageBuilder.withPayload(message).build(),
                rocketMQTemplate.getProducer().getSendMsgTimeout(),
                delayLevel);
    }

    /**
     * 异步发送消息
     */
    public void sendAsyncMessage(String topic,String tag, TestMessage message) {
        String destination = topic + ":" + tag;
        rocketMQTemplate.asyncSend(destination, MessageBuilder.withPayload(message).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {

                System.out.println("异步消息发送成功: " + sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("异步消息发送失败: " + throwable.getMessage());
                // 处理发送失败逻辑
            }
        });
    }

    /**
     * 发送单向消息（不关心发送结果）
     */
    public void sendOnewayMessage(String topic, String message) {
        rocketMQTemplate.sendOneWay(topic, MessageBuilder.withPayload(message).build());
    }

    /**
     * 顺序发送
     */
    public void sendSyncOrderlyMessage(String topic, TestMessage message) {
        rocketMQTemplate.asyncSendOrderly(topic,
                MessageBuilder.withPayload(message).build(),
                "orderly",  // 这里设置hashKey - 使用业务ID如订单号 接收者也需要设置一样
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.println("sendSyncOrderlyMessage-顺序消息-发送成功---");
                    }

                    @Override
                    public void onException(Throwable e) {
                        e.printStackTrace();
                    }
                });
    }
}